package com.innovation.ic.b1b.framework.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.function.Supplier;

/**
 * @ClassName ImgUtil
 * @Description 操作图片的工具
 * @Date 2022/10/20
 * @Author myq
 */
public class ImgUtil {


    /**
     * @Description: 探测图片是否存在
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/10/2011:06
     */
    private static boolean requireExists(String imgUrl) {
        boolean flag = false;
        URL url = null;
        try {
            url = new URL(imgUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return flag;
        }
        //打开连接
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
            return flag;
        }
        //设置请求方式为"HEAD",进行探测
        try {
            conn.setRequestMethod("HEAD");
        } catch (ProtocolException e) {
            e.printStackTrace();
            return flag;
        }

        //超时响应时间为10秒
        conn.setConnectTimeout(10 * 1000);
        //通过输入流获取图片数据
        InputStream is = null;
        try {
            is = conn.getInputStream();
        } catch (IOException e) {
            flag = true;
            //发生错误说明，图片不存在
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }


    /**
     * @ClassName ImgUtil
     * @Description 探测是否存在
     * @Date 2022/10/20
     * @Author myq
     */
    public static class Survey extends ImgUtil {

//        private T t;
//        private R r;
//        public C(T t,R r){
//            this.r = r;
//            this.t = t;
//        }

        /**
         * @Description: 返回失效列表
         * @Params:
         * @Return:
         * @Author: Mr.myq
         * @Date: 2022/10/2011:27
         */
        public boolean surveyImg(Supplier<String> lambda) {
            return requireExists(lambda.get());
        }

    }


}
